package com.cj.minio.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cj.common.response.Result;
import com.cj.minio.entity.Bucket;
import com.cj.minio.entity.FileInfo;
import com.cj.minio.service.BucketService;
import com.cj.minio.service.FileInfoService;
import com.cj.minio.service.MinioService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

/**
 * @author Mjg
 * @QQ:2091864671
 * @Create by mjg ON 2021/5/21-16:39
 */
@RestController
@RequestMapping(value = "/minio")
public class MinioController {

    @Resource
    private MinioService minioService;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private BucketService bucketService;

    @RequestMapping(value = "/uploadUrl", method = {RequestMethod.GET})
    public Result uploadUrl(@RequestParam("fileName") String fileName) {
        String policyUrl = minioService.getPolicyUrl(fileName, 2, TimeUnit.DAYS);
        return Result.success(policyUrl);
    }

    /**
     * 上传
     *
     * @param file 文件
     * @return {@link Result<String>}
     */
    @RequestMapping(value = "/upload", headers = "content-type=multipart/form-data", method = {RequestMethod.POST})
    public Result<String> upload(@Validated @NotNull(message = "文件不能为空") @RequestPart("file") MultipartFile file) {
        String image = minioService.upload(file);
        return Result.success(image);
    }

    @RequestMapping(value = "/createBucket", method = {RequestMethod.POST})
    public Result createBucket(@RequestBody Bucket bucket) {
        if (minioService.makeBucket(bucket.getBucketName())) {
            bucketService.save(bucket);
        }
        return Result.success("创建成功");
    }

    @RequestMapping(value = "/getFileUrl", method = {RequestMethod.GET})
    public Result getFileUrl(String objectName) {
        LambdaQueryWrapper<FileInfo> queryWrapper = Wrappers.lambdaQuery(FileInfo.class)
                .eq(FileInfo::getFileName, objectName);
        FileInfo fileInfo = fileInfoService.getOne(queryWrapper);
        return Result.success(fileInfo);
    }

}
